package com.example.demo.chat;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ChatController {

    @Value("${deepseek.api.key}")
    private String apiKey;

    private final RestTemplate restTemplate = new RestTemplate();

    @PostMapping("/api/chat")
    public Map<String, String> chat(@RequestBody Map<String, String> request) {
        Map<String, String> response = new HashMap<>();
        
        try {
            // 调用deepseek R1模型API
            String apiUrl = "https://api.deepseek.com/v1/chat/completions";
            
            Map<String, Object> apiRequest = new HashMap<>();
            apiRequest.put("model", "deepseek-chat");
            apiRequest.put("messages", new Object[]{
                Map.of("role", "user", "content", request.get("message"))
            });
            apiRequest.put("Stream", false);
            
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + apiKey);
            headers.set("Content-Type", "application/json");
            
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(apiRequest, headers);
            ResponseEntity<Map> responseEntity = restTemplate.postForEntity(apiUrl, requestEntity, Map.class);
            Map apiResponse = responseEntity.getBody();
            
            // 解析API响应
            String answer = ((Map)((Map)((java.util.List)apiResponse.get("choices")).get(0)).get("message")).get("content").toString();
            response.put("response", answer);
        } catch (Exception e) {
            response.put("response", "调用deepseek API时出错: " + e.getMessage());
        }
        
        return response;
    }
}
